package com.zhentao.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.device.service.WaterQualityAnomalyService;
import com.zhentao.device.mapper.WaterQualityAnomalyMapper;
import com.zhentao.device.mapper.WaterAnomalyLogMapper;
import com.zhentao.device.websocket.AlertWebSocketHandler;
import com.zhentao.pojo.WaterQualityAnomaly;
import com.zhentao.pojo.WaterAnomalyLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author DELL
* @description 针对表【water_quality_anomaly(水质告警数据表)】的数据库操作Service实现
* @createDate 2025-09-23 10:40:59
*/
@Service
public class WaterQualityAnomalyServiceImpl extends ServiceImpl<WaterQualityAnomalyMapper, WaterQualityAnomaly>
    implements WaterQualityAnomalyService {

    @Autowired
    private WaterAnomalyLogMapper waterAnomalyLogMapper;

    @Override
    public void generateAlert(String indicator, Double currentValue, String normalRange, 
                            String deviceId, String deviceName, Long dataId) {
        try {
            WaterQualityAnomaly alert = new WaterQualityAnomaly();
            
            // 设置数据库字段
            alert.setDeviceId(deviceId);
            alert.setDataId(dataId != null ? dataId : 0L); // 使用传入的dataId，如果为null则使用0
            alert.setIndicatorCode(indicator);
            alert.setCurrentValue(BigDecimal.valueOf(currentValue));
            alert.setNormalRange(normalRange);
            alert.setAnomalyType(1); // 默认超标类型
            alert.setSeverity(determineSeverity(indicator, currentValue, normalRange));
            alert.setHandleStatus(1); // 未处理
            alert.setCreateTime(new Date());
            
            this.save(alert);
            System.out.println("✅ 生成告警: " + indicator + "异常 (ID: " + alert.getAnomalyId() + ")");
            
            // 自动创建警告日志记录
            try {
                createAlertLog(alert.getAnomalyId(), 1, "系统监测到异常数据，自动创建警告");
                System.out.println("📝 已创建警告日志记录，告警ID: " + alert.getAnomalyId());
            } catch (Exception logError) {
                System.err.println("❌ 创建警告日志失败: " + logError.getMessage());
            }
            
            // 通过WebSocket实时推送告警
            try {
                AlertWebSocketHandler.broadcastNewAlert(alert);
                System.out.println("📡 告警已推送到WebSocket客户端");
            } catch (Exception wsError) {
                System.err.println("❌ WebSocket推送失败: " + wsError.getMessage());
            }
            
        } catch (Exception e) {
            System.err.println("❌ 生成告警失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public boolean updateAlertStatus(Long alertId, Integer status, String handlerId) {
        try {
            int updated = baseMapper.updateStatus(alertId, status, handlerId);
            if (updated > 0) {
                System.out.println("✅ 更新告警状态: " + alertId + " -> " + status);
                
                // 自动创建状态更新日志记录
                try {
                    String description = getStatusDescription(status);
                    createAlertLog(alertId, status, description);
                    System.out.println("📝 已创建状态更新日志记录，告警ID: " + alertId + ", 状态: " + status);
                } catch (Exception logError) {
                    System.err.println("❌ 创建状态更新日志失败: " + logError.getMessage());
                }
                
                // 通过WebSocket推送状态更新
                try {
                    AlertWebSocketHandler.broadcastAlertUpdate(alertId, status, handlerId);
                    System.out.println("📡 告警状态更新已推送到WebSocket客户端");
                } catch (Exception wsError) {
                    System.err.println("❌ WebSocket推送失败: " + wsError.getMessage());
                }
                
                return true;
            }
            return false;
        } catch (Exception e) {
            System.err.println("❌ 更新告警状态失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public int batchHandleAlerts(List<Long> alertIds, Integer status, String handlerId) {
        try {
            int successCount = baseMapper.batchUpdateStatus(alertIds, status, handlerId);
            System.out.println("✅ 批量处理告警: " + successCount + "/" + alertIds.size());
            return successCount;
        } catch (Exception e) {
            System.err.println("❌ 批量处理告警失败: " + e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<WaterQualityAnomaly> getAlertsByStatus(Integer status) {
        return baseMapper.selectByStatus(status);
    }

    @Override
    public Map<String, Integer> getAlertStats() {
        Map<String, Object> result = baseMapper.selectAlertStats();
        Map<String, Integer> stats = new HashMap<>();
        
        // 检查结果是否为空
        if (result != null) {
            // 转换结果类型
            stats.put("total", result.get("total") != null ? ((Number) result.get("total")).intValue() : 0);
            stats.put("unhandled", result.get("unhandled") != null ? ((Number) result.get("unhandled")).intValue() : 0);
            stats.put("confirmed", result.get("confirmed") != null ? ((Number) result.get("confirmed")).intValue() : 0);
            stats.put("handled", result.get("handled") != null ? ((Number) result.get("handled")).intValue() : 0);
        } else {
            // 如果查询结果为空，返回默认值
            stats.put("total", 0);
            stats.put("unhandled", 0);
            stats.put("confirmed", 0);
            stats.put("handled", 0);
        }
        
        return stats;
    }

    @Override
    public List<WaterQualityAnomaly> getAlertsByDeviceId(String deviceId) {
        return baseMapper.selectByDeviceId(deviceId);
    }

    @Override
    public List<WaterQualityAnomaly> getAlertsByIndicator(String indicator) {
        return baseMapper.selectByIndicator(indicator);
    }

    /**
     * 根据严重程度确定告警级别
     */
    private Integer determineSeverity(String indicator, Double currentValue, String normalRange) {
        try {
            String[] range = normalRange.split("-");
            if (range.length != 2) return 2; // 默认中等
            
            double min = Double.parseDouble(range[0]);
            double max = Double.parseDouble(range[1]);
            double deviation = Math.min(Math.abs(currentValue - min), Math.abs(currentValue - max));
            double rangeSize = max - min;
            double deviationPercent = deviation / rangeSize;
            
            if (deviationPercent > 0.5) return 3; // 严重
            if (deviationPercent > 0.2) return 2; // 中等
            return 1; // 轻微
        } catch (NumberFormatException e) {
            return 2; // 默认中等
        }
    }
    
    /**
     * 创建警告日志记录
     * @param anomalyId 异常ID
     * @param status 状态
     * @param description 描述
     */
    private void createAlertLog(Long anomalyId, Integer status, String description) {
        try {
            WaterAnomalyLog log = new WaterAnomalyLog();
            log.setAnomalyId(anomalyId.intValue());
            log.setStatus(status);
            log.setCreateTime(new Date());
            
            waterAnomalyLogMapper.insert(log);
            System.out.println("📝 警告日志已创建: 异常ID=" + anomalyId + ", 状态=" + status + ", 描述=" + description);
        } catch (Exception e) {
            System.err.println("❌ 创建警告日志失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 根据状态获取描述
     * @param status 状态
     * @return 描述
     */
    private String getStatusDescription(Integer status) {
        if (status == null) return "系统监测到异常数据，自动创建警告";
        
        switch (status) {
            case 1:
                return "系统监测到异常数据，自动创建警告";
            case 2:
                return "警告已确定，正在去往现场";
            case 3:
                return "警告已解决";
            default:
                return "系统监测到异常数据，自动创建警告";
        }
    }
}




